package com.donlim.dev.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donlim.dev.dto.sql.QueryWrapperAndPage;
import com.donlim.dev.dto.sql.SQLParam;
import com.donlim.dev.dto.sql.SQLParams;

/**
 * Created by 星 on 2020/11/3
 */
public class SQLUtils {
    public static <T> QueryWrapperAndPage getQueryWrapperAndPage(SQLParams sqlParams){

        //查询条件构造
        QueryWrapperAndPage queryWrapperAndPage = new QueryWrapperAndPage();
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        queryWrapper.allEq(sqlParams.getAllEq(),false);
        if (sqlParams.getNe()!= null){
            for (SQLParam sqlParam : sqlParams.getNe()) {
                queryWrapper.ne(sqlParam.getVal1()==null? false: true, sqlParam.getColumn(),sqlParam.getVal1());
            }
        }
        if (sqlParams.getGt()!=null){
            for (SQLParam sqlParam : sqlParams.getGt()) {
                queryWrapper.gt(sqlParam.getVal1()==null?false:true, sqlParam.getColumn(),sqlParam.getVal1());
            }
        }
        if (sqlParams.getLt()!=null){
            for (SQLParam sqlParam : sqlParams.getLt()) {
                queryWrapper.lt(sqlParam.getVal1()==null?false:true, sqlParam.getColumn(),sqlParam.getVal1());
            }
        }
        if (sqlParams.getBetween()!=null){
            for (SQLParam sqlParam : sqlParams.getBetween()) {
                queryWrapper.between((sqlParam.getVal1()==null||sqlParam.getVal2()==null)? false:true, sqlParam.getColumn(),sqlParam.getVal1(),sqlParam.getVal2());
            }
        }
        if (sqlParams.getNotBetween()!=null){
            for (SQLParam sqlParam : sqlParams.getNotBetween()) {
                queryWrapper.notBetween((sqlParam.getVal1()==null||sqlParam.getVal2()==null)? false:true,sqlParam.getColumn(),sqlParam.getVal1(),sqlParam.getVal2());
            }
        }
        if (sqlParams.getLike()!=null){
            for (SQLParam sqlParam : sqlParams.getLike()) {
                queryWrapper.like(sqlParam.getVal1()==null?false:true, sqlParam.getColumn(),sqlParam.getVal1());
            }
        }
        if (sqlParams.getOrderByAsc()!=null){
            queryWrapper.orderByAsc(sqlParams.getOrderByAsc());
        }
        if (sqlParams.getOrderByDesc()!=null){
            queryWrapper.orderByDesc(sqlParams.getOrderByDesc());
        }

        //分页
        Page<T> page = null;
        if (sqlParams.isPage()){
            if (sqlParams.getCurrent() != null || sqlParams.getSize() != null){
                page = new Page<>(sqlParams.getCurrent(),sqlParams.getSize());
            }else {
                page = new Page<>(1,10);
            }
        }
        queryWrapperAndPage.setPage(page);
        queryWrapperAndPage.setQueryWrapper(queryWrapper);
        return queryWrapperAndPage;
    }

}
